package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.common.dto.BaseDTO;
import com.leyou.common.exception.LyException;
import com.leyou.item.dto.BrandDTO;
import com.leyou.item.dto.PageDTO;
import com.leyou.item.dto.QueryPageBean;
import com.leyou.item.entity.Brand;
import com.leyou.item.entity.CategoryBrand;
import com.leyou.item.mapper.BrandMapper;
import com.leyou.item.service.BrandService;
import com.leyou.item.service.CategoryBrandService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author YYP
 * @date 2020/12/28
 */
@Service
public class BrandServiceImpl extends ServiceImpl<BrandMapper, Brand> implements BrandService {

    @Autowired
    private CategoryBrandService categoryBrandService;

    /**
     * 根据品牌id集合查询品牌集合
     * @param ids
     * @return
     */
    @Override
    public List<BrandDTO> listBrandByIds(List<Long> ids) {

        return BrandDTO.convertEntityList(this.listByIds(ids));
    }

    /**
     * 根据id删除品牌
     * @param id
     */
    @Override
    public void deleteBrandById(Long id) {
        //1.删除品牌表
        boolean success = this.removeById(id);
        if (!success) {
            // 更新失败，抛出异常
            throw new LyException(500, "删除品牌失败！");
        }
        //2.删除中间表
        QueryWrapper<CategoryBrand> wrapper = new QueryWrapper<>();
        wrapper.eq("brand_id",id);
        categoryBrandService.remove(wrapper);


    }

    /**
     * 更新品牌
     * @param brandDTO
     */
    @Override
    public void updateBrand(BrandDTO brandDTO) {
        //1.更新品牌表
        Brand brand = brandDTO.toEntity(Brand.class);
        boolean success = this.updateById(brand);
        if (!success) {
            // 更新失败，抛出异常
            throw new LyException(500, "更新品牌失败！");
        }

        //2.删除中间表,根据品牌id删除中间表数据
        QueryWrapper<CategoryBrand> wrapper = new QueryWrapper<>();
        wrapper.eq("brand_id",brand.getId());
        boolean sucess = categoryBrandService.remove(wrapper);
        if (!success) {
            // 更新失败，抛出异常
            throw new LyException(500,"更新品牌失败，删除中间表数据出错");
        }
        //3.更新中间表
        List<Long> categoryIds = brandDTO.getCategoryIds();
        Long brandId = brand.getId();
        ArrayList<CategoryBrand> categoryBrands = new ArrayList<>();
        for (Long categoryId : categoryIds) {
            CategoryBrand categoryBrand = CategoryBrand.of(categoryId, brandId);
            categoryBrands.add(categoryBrand);
        }
        categoryBrandService.saveBatch(categoryBrands);
    }

    /**
     * 新增品牌
     * @param brandDTO
     * @return
     */
    @Override
    @Transactional
    public void addBrand(BrandDTO brandDTO) {

        Brand brand = brandDTO.toEntity(Brand.class);
        this.save(brand);

        //2.获取分类id，
        List<Long> categoryIds = brandDTO.getCategoryIds();
        //3.封装中间表对象集合
        Long brandId = brand.getId();

        ArrayList<CategoryBrand> categoryBrands = new ArrayList<>();
        for (Long categoryId : categoryIds) {
            //创建中间表对象
            CategoryBrand categoryBrand = CategoryBrand.of(categoryId, brandId);
            categoryBrands.add(categoryBrand);
        }
        // 批量写入中间表数据
        categoryBrandService.saveBatch(categoryBrands);

    }

    @Override
    public List<BrandDTO> listBrandByCategoryId(Long categoryId) {
       // List<Brand> brandList = baseMapper.listBrandByCategoryId(categoryId);

        //1.根据分类id，查询中间表，得到表对象集合
        List<CategoryBrand> categoryBrandList = categoryBrandService.query().eq("category_id", categoryId).list();
        if (CollectionUtils.isEmpty(categoryBrandList)){
            return Collections.emptyList();
        }
        //2.获取品牌id集合
        ArrayList<Long> brandIdList = new ArrayList<>();
        for (CategoryBrand categoryBrand : categoryBrandList) {
            brandIdList.add(categoryBrand.getBrandId());
        }
        //3.根据品牌id集合，查询品牌对象集合
        List<Brand> brandList = this.listByIds(brandIdList);
        //4.装换DTO
        List<BrandDTO> brandDTOList = BrandDTO.convertEntityList(brandList);
        return brandDTOList;
    }

    /**
     * 分页查询品牌
     * @param
     * @return
     */
    @Override
    public PageDTO<BrandDTO> queryBrandByPage(QueryPageBean queryPageBean) {
        //1.分页信息的健壮性处理
        Integer page = queryPageBean.getPage();
        Integer rows = queryPageBean.getRows();
        String key = queryPageBean.getKey();
        //1.分页信息的健壮性处理
        page = Math.min(page,100);
        rows = Math.max(rows,5);
        //2.分页
        Page<Brand> brandPage = this.page(new Page<>(page, rows));
        //3.判断key是否存在
        boolean isKeyExists = StringUtils.isNoneBlank(key);
        //4.如果key存在，添加like和eq的查询条件。否则不添加
        query().like(isKeyExists,"name",key).or()
                .eq(isKeyExists,"letter",key)
                .page(brandPage);
        //5.封装结果
        List<Brand> list = brandPage.getRecords();
        return new PageDTO<>(brandPage.getTotal(),brandPage.getPages(),BrandDTO.convertEntityList(list));
    }



    /**
     * 分页查询
     * @param page
     * @param rows
     * @param key
     * @return
     */
    @Override
    public PageDTO<BrandDTO> queryBrandByPage(Integer page, Integer rows, String key) {
        //1.分页信息的健壮性处理
        page = Math.min(page,100);
        rows = Math.max(rows,5);
        //2.分页
        Page<Brand> brandPage = new Page<>(page, rows);
        //3.判断key是否存在，动态sql，只有condition为true，自定义查询才会生效
        boolean condition = StringUtils.isNoneBlank(key);
        //4.如果key存在，添加like和eq的查询条件。否则不添加
        page(brandPage,
                new QueryWrapper<Brand>()
                        .like(condition, "name", key)
                        .or()
                        .eq(condition, "letter", key));

        //5.封装结果
        List<Brand> list = brandPage.getRecords();
        return new PageDTO<>(brandPage.getTotal(),brandPage.getPages(),BrandDTO.convertEntityList(list));

    }

/*    @Override
    public PageDTO<BrandDTO> queryBrandByPage(Integer page, Integer rows, String key) {
        //1.分页
        //2.判断key是否存在
        QueryWrapper<Brand> wrapper = new QueryWrapper<>();
        if (StringUtils.isNoneBlank(key)){
            wrapper.like("name",key).or()
                    .eq("letter",key);
        }
        Page<Brand> brandPage = this.page(new Page<>(page, rows),wrapper);
        //3.封装结果
        return new PageDTO<BrandDTO>(brandPage.getTotal(),brandPage.getPages(),BrandDTO.convertEntityList(brandPage.getRecords()));
    }*/

    /**
     * 根据id查询品牌
     * @param id
     * @return
     */
    @Override
    public BrandDTO queryBrandById(Long id) {
        Brand brand = this.getById(id);
        BrandDTO brandDTO = new BrandDTO(brand);
        return brandDTO;
    }
}
